﻿using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;

namespace UDPSocketProject
{
    public class DataFrameConverter
    {
        public static DataFrameHeaderModel ConvertDataFrame(byte[] convertData, int byteDataLength)
        {
            DataFrameHeaderModel dataFrameHeaderModel = new DataFrameHeaderModel();
            DataFrameHeaderEnum header = (DataFrameHeaderEnum)Converter.BytesToStruct(convertData, typeof(DataFrameHeaderEnum));

            dataFrameHeaderModel.mark = header.mark;
            dataFrameHeaderModel.devid = header.devid;
            dataFrameHeaderModel.devmac = BitConverter.ToString(header.devmac);
            dataFrameHeaderModel.longitude = Double.Parse(header.longitude);
            dataFrameHeaderModel.latitude = Double.Parse(header.latitude);
            dataFrameHeaderModel.datalen = Converter.ReverseBytes(header.data_len);
            dataFrameHeaderModel.dataFrameList = new List<DataFrameModel>();

            Int32 dataFrameHeaderSize = Marshal.SizeOf(typeof(DataFrameHeaderEnum));

            Int32 frameDataSize = Marshal.SizeOf(typeof(FrameDataEnum));

            Console.WriteLine("------------服务器收到的 header 数据:-------------");
            Console.WriteLine("mark:{0} \n devid: {1} \n devmac:{2} \n latitude:{3} \n longitude:{4} \n data_len:{5}",header.mark,header.devid,BitConverter.ToString(header.devmac),header.latitude,header.latitude,header.longitude,Converter.ReverseBytes(header.data_len));

            Int32 point = 0;
            do
            {
                FrameDataEnum frameData = (FrameDataEnum)Converter.BytesToStructoffset(convertData, dataFrameHeaderSize + point, typeof(FrameDataEnum));

                DataFrameModel dataFrameModel = new DataFrameModel();
                dataFrameModel.stamac = BitConverter.ToString(frameData.sta_mac);
                dataFrameModel.apmac = BitConverter.ToString(frameData.ap_mac);
                dataFrameModel.ssid = frameData.ssid;
                dataFrameModel.rssi = Converter.BLEndianUshort(frameData.rssi);
                dataFrameModel.channel = Converter.ReverseBytes(frameData.channel);
                dataFrameHeaderModel.dataFrameList.Add(dataFrameModel);

                Console.WriteLine("--服务器收到的 frameData 数据:");
                Console.WriteLine("sta_mac: {0} \n ap_mac:{1} \n ssid:{2} \n rssi:{3} \n channel:{4}", dataFrameModel.stamac,dataFrameModel.apmac,dataFrameModel.ssid,dataFrameModel.rssi,dataFrameModel.channel);
                point += frameDataSize;
            } while ((byteDataLength - dataFrameHeaderSize - point) > 0);

            return dataFrameHeaderModel;
        }
    }
}
